package main

import (
	"context"
	"errors"
	"fmt"
	"golang.org/x/sync/errgroup"
	"io"
	"net/http"
	"os"
	"os/signal"
)

func main() {
	gox, ctx := errgroup.WithContext(context.Background())

	srv := &http.Server{Addr: ":9090"}
	//启动http server
	gox.Go(func() error {
		http.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request) {
			io.WriteString(w, "this is a http server!\n")
		})
		err := srv.ListenAndServe()
		return err
	})

	//关闭http server
	gox.Go(func() error {
		<-ctx.Done()
		fmt.Println("http server stop")
		return srv.Shutdown(ctx) // 关闭 http server
	})


	//signal 信号的注册和处理
	gox.Go(func() error {
		quit := make(chan os.Signal, 1)
		signal.Notify(quit)
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-quit:
			return errors.New("quit reason: get quit signal")
		}
	})

	if err := gox.Wait(); err != nil {
		fmt.Println("get gox error: ", err)
	} else {
		fmt.Println("all gox has done!")
	}

}